home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7371 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: CES.CWRU.Edu!calvitti
  2. From: calvitti@yuggoth.ces.cwru.edu (AC)
  3. Newsgroups: sci.math.num-analysis,comp.lang.c++
  4. Subject: [Q] Moving invariant code out of loops?
  5. Followup-To: sci.math.num-analysis
  6. Date: 23 Feb 1996 00:10:50 GMT
  7. Organization: Case Western Reserve University
  8. Distribution: inet
  9. Message-ID: <CALVITTI.96Feb22191050@yuggoth.ces.cwru.edu>
  10. NNTP-Posting-Host: yuggoth.ces.cwru.edu
  11.  
  12. i was wondering if any C/C++ compilers can move invariant code out of
  13. loops, like the assert calls in operations like the following
  14. simple example:
  15.  
  16.     ...  
  17.  
  18. //////////////////////////////////////////
  19. inline double Vector::operator[](int i)
  20. {
  21.   assert(i >= 0 && i < size());
  22.   return data_array[i];
  23. }
  24.  
  25. // ... assume friend of Vector
  26. //////////////////////////////////////////
  27. double inner_product(Vector& a, Vector& b)
  28. {
  29.   double tmp = 0;
  30.   assert(a.size() == b.size());
  31.   for(int i=0;i<a.size();i++)
  32.     tmp += a[i] * b[i];
  33.   return tmp;
  34. }
  35.  
  36. since the index 'i' in 'inner_product' does not violate the assertion
  37. called in 'Vector::operator[]', the latter imposes redundant overhead
  38. on the routine. can/do (C/C++) compilers optimize this away? IMO, this
  39. seems a hard problem in general, since for example, the 'b[i]'
  40. invariance assumes not only the structure of that for loop but also
  41. that 'a.size() == b.size()'.
  42.  
  43. of course, an inelegant solution is to define an alternative
  44. (protected or private) element getter which does not call 'assert',
  45. but that, imo, is inelegant and unsafe, since a lot of time and effort
  46. is spent writing member functions (or friends) themselves.
  47.  
  48. also, are exception mechanisms faster for this kind of functionality?
  49.  
  50. if not, are there languages/implementations that can do this? 
  51.  
  52. thanks for the information,
  53.  
  54. alan
  55.  
  56.  +---------------------------------+
  57.  |          Alan Calvitti          |
  58.  |       Control Engineering       |
  59.  | Case Western Reserve University |
  60.  +---------------------------------+
  61.  
  62.  
  63.